﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace CommonLib.Util
{
	static public class Collider2DUtil
	{
		static public bool Box2DFindNearest(Vector2 center, Vector2 size, Func<Collider2D, bool> checker, out Collider2D collider)
		{
			collider = null;
			float length = float.MaxValue;
			Collider2D[] colliders = Physics2D.OverlapBoxAll(center, size, 0);
			if (colliders.Length < 0)
			{
				return false;
			}
			else
			{
				for (int index = 0; index < colliders.Length; index++)
				{
					if (checker(colliders[index]))
					{
						float diatance = Vector3.Distance(center, colliders[index].transform.position);
						if (diatance < length)
						{
							collider = colliders[index];
							length = diatance;
						}
					}
				}
				if (null != collider) return true;
			}

			return false;
		}

		static public bool Box2DFindFarest(Vector2 center, Vector2 size, Func<Collider2D, bool> checker, out Collider2D collider)
		{
			collider = null;
			float length = 0;
			Collider2D[] colliders = Physics2D.OverlapBoxAll(center, size, 0);
			if (colliders.Length < 0)
			{
				return false;
			}
			else
			{
				for (int index = 0; index < colliders.Length; index++)
				{
					if (checker(colliders[index]))
					{
						float diatance = Vector3.Distance(center, colliders[index].transform.position);
						if (diatance > length)
						{
							collider = colliders[index];
							length = diatance;
						}
					}
				}
				if (null != collider) return true;
			}

			return false;
		}

		static public bool Box2DFindAll(Vector2 center, Vector2 size, Func<Collider2D, bool> checker, out Collider2D[] cols)
		{
			List<Collider2D> lstCol = new List<Collider2D>();
			cols = null;

			Collider2D[] colliders = Physics2D.OverlapBoxAll(center, size, 0);
			if (colliders.Length < 0)
			{
				return false;
			}
			else
			{
				for (int index = 0; index < colliders.Length; index++)
				{
					if (checker(colliders[index]))
					{
						lstCol.Add(colliders[index]);
					}
				}
				if (null != lstCol && lstCol.Count > 0) {
					cols = lstCol.ToArray();
					return true;
				}
			}

			return false;
		}
	}
}